//package com.plian.system.service.im.impl;
//
//import com.alibaba.excel.EasyExcel;
//import com.alibaba.excel.read.listener.PageReadListener;
//import com.alibaba.fastjson.JSON;
//import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
//import com.plian.Tools.*;
//import com.plian.Tools.pagedata.PageData;
//import com.plian.system.bean.pf.NegativeForbidExcelBean;
//import com.plian.system.bean.pf.NegativeInvestmentExcelBean;
//import com.plian.system.bean.pf.NegativeSuperviseExcelBean;
//import com.plian.system.cache.UserCache;
//import com.plian.system.common.status.CheckStatus;
//import com.plian.system.constant.sys.FormStatusConstant;
//import com.plian.system.constant.sys.FormTypeConstant;
//import com.plian.system.constant.yth.YthConstant;
//import com.plian.system.entity.im.NegativeForbid;
//import com.plian.system.entity.im.NegativeInvestment;
//import com.plian.system.entity.im.NegativeSupervise;
//import com.plian.system.entity.sys.ApprovalMessage;
//import com.plian.system.excel.ImportExcelUtil;
//import com.plian.system.mapper.im.NegativeInvestmentMapper;
//import com.plian.system.mybatis.base.BaseFlowService;
//import com.plian.system.mybatis.base.BaseServiceImpl;
//import com.plian.system.mybatis.support.Condition;
//import com.plian.system.service.im.NegativeForbidService;
//import com.plian.system.service.im.NegativeInvestmentService;
//import com.plian.system.service.im.NegativeSuperviseService;
//import com.plian.system.service.sys.message.IApprovalMessageService;
//import com.plian.system.service.sys.orgzation.IOrgService;
//import com.plian.system.service.sys.user.ISysUserService;
//import com.plian.system.vo.im.NegativeInvestmentVO;
//import com.plian.system.vo.yth.YthResult;
//import com.plian.system.wrapper.im.NegativeInvestmentWrapper;
//import lombok.AllArgsConstructor;
//import org.apache.commons.io.IOUtils;
//import org.apache.commons.lang.exception.ExceptionUtils;
//import org.apache.commons.lang3.StringUtils;
//import org.springframework.stereotype.Service;
//import org.springframework.transaction.annotation.Transactional;
//import org.springframework.web.multipart.MultipartFile;
//
//import java.io.ByteArrayInputStream;
//import java.io.IOException;
//import java.io.InputStream;
//import java.util.*;
//import java.util.stream.Collectors;
//
//import static com.plian.system.constant.sys.ApprovalMessageTypeConstant.INVESTMENT_EXECUTION;
//import static com.plian.system.constant.sys.ApprovalMessageTypeConstant.KT_TYPE;
//import static com.plian.system.constant.sys.FormStatusConstant.UNREVIEWED;
//
//@Service
//@AllArgsConstructor
//public class NegativeInvestmentServiceImpl extends BaseServiceImpl<NegativeInvestmentMapper, NegativeInvestment> implements NegativeInvestmentService, BaseFlowService {
//
//    private final NegativeForbidService negativeForbidService;
//
//    private final NegativeInvestmentWrapper negativeInvestmentWrapper;
//
//    private final NegativeSuperviseService negativeSuperviseService;
//
//    private IOrgService orgService;
//
//    private ISysUserService userService;
//
//    private IApprovalMessageService approvalMessageService;
//    @Override
//    public boolean saveOrUpdate(NegativeInvestment negativeInvestment) {
//        if (!Optional.ofNullable(negativeInvestment.getStatus()).isPresent()) {
//            negativeInvestment.setStatus(FormStatusConstant.UNREVIEWED);
//        }
//        if (!Optional.ofNullable(negativeInvestment.getId()).isPresent()) {
//            negativeInvestment.setFormType(String.valueOf(FormTypeConstant.IM_NEGATIVE_INVESTMENT));
//        }
//        return super.saveOrUpdate(negativeInvestment);
//    }
//
//    @Override
//    @Transactional(rollbackFor=RuntimeException.class)
//    public boolean deleteLogic(List<Long> ids) {
//        for (Long id : ids) {
//            NegativeInvestment negativeInvestment = getById(id);
//            if (negativeInvestment == null) {
//                return false;
//            }
//        }
//        boolean result = super.deleteLogic(ids);
//        if (result){
//            negativeForbidService.deleteByParentId(ids);
//            negativeForbidService.deleteByParentId(ids);
//        }
//        return result;
//    }
//
//    @Override
//    @Transactional(rollbackFor=RuntimeException.class)
//    public boolean submit(NegativeInvestment negativeInvestmente) {
//        boolean result = saveOrUpdate(negativeInvestmente);
//        if(result){
//            List<NegativeForbid> negativeForbids = negativeInvestmente.getNegativeForbid();
//            if(CollectionUtil.isNotEmpty(negativeForbids)){
//                for (NegativeForbid negativeForbid : negativeForbids) {
//                    if(negativeForbid.getId()!= null &&
//                           Optional.ofNullable(negativeForbid.getIsDeleted()).isPresent() && negativeForbid.getIsDeleted().intValue() == 1){
//                        negativeForbidService.removeById(negativeForbid.getId());
//                    }else {
//                        negativeForbid.setTypeId(negativeInvestmente.getId());
//                        negativeForbidService.saveOrUpdate(negativeForbid);
//                    }
//                }
//            }
//            List<NegativeSupervise> negativeSupervises = negativeInvestmente.getNegativeSupervises();
//            if(CollectionUtil.isNotEmpty(negativeSupervises)){
//                for (NegativeSupervise sons : negativeSupervises) {
//                    if(sons.getId()!= null &&
//                            Optional.ofNullable(sons.getIsDeleted()).isPresent() && sons.getIsDeleted().intValue() == 1){
//                        negativeSuperviseService.removeById(sons.getId());
//                    }else {
//                        sons.setTypeId(negativeInvestmente.getId());
//                        negativeSuperviseService.saveOrUpdate(sons);
//                    }
//                }
//            }
//        }
//        return result;
//    }
//
//    @Override
//    @Transactional(rollbackFor = RuntimeException.class)
//    public String saveInvestmentNegativeList(String data){
//        YthResult ythResult = new YthResult();
//        //成功的id集合
//        List<String> successIds = new ArrayList<>();
//        //失败的id集合
//        List<String> failIds = new ArrayList<>();
//        //失败的原因
//        List<String> failReasons = new ArrayList<>();
//        //将json字符串转换成list
//        List<NegativeInvestment> dataList = JSON.parseArray(data, NegativeInvestment.class);
//        if (CollectionUtil.isNotEmpty(dataList)){
//            Map<String, String> orgSourceMap = orgService.getSourceId();
//            Map<String, String> userSourceMap = userService.getSourceId();
//            //根据datasourceIds 查询出所有的数据
//            List<NegativeInvestment> list = list(new LambdaQueryWrapper<NegativeInvestment>().in(NegativeInvestment::getDataSourceId, dataList.stream().map(NegativeInvestment::getDataSourceId).toArray()));
//            if (CollectionUtil.isNotEmpty(list)){
//                //删除子集
//                List<Long> ids = list.stream().map(NegativeInvestment::getId).collect(Collectors.toList());
//                negativeForbidService.remove(new LambdaQueryWrapper<NegativeForbid>().in(NegativeForbid::getTypeId, ids));
//                negativeSuperviseService.remove(new LambdaQueryWrapper<NegativeSupervise>().in(NegativeSupervise::getTypeId, ids));
//            }
//            //如果数据库中有数据，就更新，没有就新增
//            for (NegativeInvestment entity:dataList){
//                transfer(entity,orgSourceMap,userSourceMap);
//                //id重复略过
//                if (CollectionUtil.isNotEmpty(list)){
//                    List<String> olIds = list.stream().map(NegativeInvestment::getDataSourceId).collect(Collectors.toList());
//                    String dataSourceId = entity.getDataSourceId();
//                    //判断数据库中是否有数据
//                    if (olIds.contains(dataSourceId)){
//                        for (NegativeInvestment oldEntity:list){
//                            if (dataSourceId.equals(oldEntity.getDataSourceId())){
//                                //判断status是否为0，如果是0，就更新，不是0，就不更新
//                                if (CheckStatus.checkCode(oldEntity.getStatus())){
//                                    successIds.add(dataSourceId);
//                                    entity.setId(oldEntity.getId());
//                                    entity.setDataSource(YthConstant.DATA_NINGBO);
//                                    submit(entity);
//                                    list.remove(oldEntity);
//                                    break;
//                                }else {
//                                    failIds.add(dataSourceId);
//                                    failReasons.add("dataSourceId:"+dataSourceId+"数据已提交且已经在流程中，无法更新");
//                                    break;
//                                }
//                            }
//                        }
//                    }else {
//                        //如果数据库中没有数据，就新增
//                        entity.setDataSource(YthConstant.DATA_NINGBO);
//                        submit(entity);
//                        successIds.add(entity.getDataSourceId());
//                    }
//                }else {
//                    //如果数据库中没有数据，就新增
//                    entity.setDataSource(YthConstant.DATA_NINGBO);
//                    submit(entity);
//                    successIds.add(entity.getDataSourceId());
//                }
//            }
//        } else {
//            failReasons.add("数据为空");
//        }
//        ythResult.setSuccessIds(successIds);
//        ythResult.setFailIds(failIds);
//        ythResult.setFailReason(StringUtils.join(failReasons, ";"));
//        //ythResult转换成json字符串
//        return JSON.toJSONString(ythResult);
//    }
//
//    private void transfer(NegativeInvestment entity, Map<String, String> orgSourceMap,Map<String, String> userSourceMap){
//        Optional.ofNullable(entity.getCreateCompanyId()).ifPresent(m ->
//                {
//                    String orgId = orgSourceMap.get(m);
//                    if (StringUtil.isNotBlank(orgId)){
//                        entity.setCreateCompanyId(orgId);
//                    }
//                }
//        );
//        Optional.ofNullable(entity.getReportPerson()).ifPresent(m ->
//                {
//                    String userId = userSourceMap.get(m);
//                    if (StringUtil.isNotBlank(userId)){
//                        entity.setReportPerson(userId);
//                    }
//                }
//        );
//    }
//
//    @Override
//    public NegativeInvestmentVO getDetailObj(NegativeInvestment negativeInvestment) {
//        NegativeInvestment detail = getOne(Condition.getQueryWrapper(negativeInvestment));
//        NegativeInvestmentVO negativeInvestmentVO = negativeInvestmentWrapper.entityToVO(detail);
//        //子项
//        List<NegativeForbid> negativeForbids = negativeForbidService.list(new LambdaQueryWrapper<NegativeForbid>().eq(NegativeForbid::getTypeId, negativeInvestmentVO.getId()));
//        if(CollectionUtil.isNotEmpty(negativeForbids)){
//            negativeInvestmentVO.setNegativeForbid(negativeForbids);
//        }
//        List<NegativeSupervise> negativeSupervises = negativeSuperviseService.list(new LambdaQueryWrapper<NegativeSupervise>().eq(NegativeSupervise::getTypeId, negativeInvestmentVO.getId()));
//        if(CollectionUtil.isNotEmpty(negativeSupervises)){
//            negativeInvestmentVO.setNegativeSupervises(negativeSupervises);
//        }
//        return negativeInvestmentVO;
//    }
//
//    @Override
//    public HashMap<String,Object> commit(String id) {
//        handleStatus(Long.valueOf(id), FormStatusConstant.FLOW,"");
//        //将需要提交的流程变量返回，用于工作流侧
//        return new HashMap<String,Object>();
//    }
//
//    @Override
//    public Boolean finish(String id) {
//        return handleStatus(Long.valueOf(id), FormStatusConstant.FINISH,"审批通过");
//    }
//
//    @Override
//    public Boolean reject(String id, int formState, String comment) {
//        return handleStatus(Long.valueOf(id), formState, comment);
//    }
//
//    @Override
//    public void goBackToStash(String formId) {
//        handleStatus(Long.valueOf(formId), UNREVIEWED,"");
//    }
//
//    @Override
//    public List<PageData> findByIds(List<String> formIds) {
//        LambdaQueryWrapper<NegativeInvestment> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.in(NegativeInvestment::getId, Func.toLongList(org.apache.commons.lang3.StringUtils.join(formIds, StringPool.COMMA)));
//        List<NegativeInvestment> negativeInvestments = list(queryWrapper);
//        List<NegativeInvestmentVO> negativeInvestmentVOS = negativeInvestmentWrapper.entityToVO(negativeInvestments);
//        List<PageData> pageDataList = new ArrayList<>();
//        try{
//            if (CollectionUtil.isNotEmpty(negativeInvestmentVOS)){
//                for (NegativeInvestmentVO vo : negativeInvestmentVOS){
//                    PageData pd = new PageData();
//                    pd.put("id", vo.getId());
//                    pd.put("UNITNAME", vo.getCreateCompanyName());
//                    pd.put("APPLICANTNAME", vo.getCreateUserName());
//                    pd.put("applicantId", vo.getCreateUser());
//                    pd.put("applyOrganizationId", vo.getCreateCompanyName());
//                    pd.put("formType", FormTypeConstant.IM_NEGATIVE_INVESTMENT);
//                    pd.put("orgName", vo.getCreateCompanyName());
//                    pageDataList.add(pd);
//                }
//            }
//            return pageDataList;
//        } catch (Exception e) {
//            log.error(ExceptionUtils.getFullStackTrace(e));
//        }
//        return pageDataList;
//    }
//
//    @Override
//    public List<Integer> getFormType() {
//        return Arrays.asList(FormTypeConstant.IM_NEGATIVE_INVESTMENT);
//    }
//
//    /**
//     * 统一处理状态机事件方法
//     *
//     * @param id          主键
//     * @param updateStatus 更新状态
//     * @return boolean
//     */
//    private Boolean handleStatus(Long id, int updateStatus,String comment) {
//        try {
//            NegativeInvestment negativeInvestment = getById(id);
//            /**
//             * 设置审批人和审批时间
//             */
//            if (updateStatus == FormStatusConstant.FINISH){
//                negativeInvestment.setApprovedUser(TokenUtil.getTokenUserId());
//                Date now = DateUtil.now();
//                negativeInvestment.setApprovedTime(now);
//            }
//
//            if (StringUtil.isNotBlank(negativeInvestment.getDataSource()) &&
//                    StringUtil.isNotBlank(negativeInvestment.getDataSourceId())){
//                if (updateStatus == FormStatusConstant.FINISH || updateStatus == FormStatusConstant.REJECT){
//                    ApprovalMessage approvalMessage = new ApprovalMessage();
//                    approvalMessage.setDataSourceId(negativeInvestment.getDataSourceId());
//                    approvalMessage.setType(INVESTMENT_EXECUTION);
//                    approvalMessage.setOpinion(comment);
//                    approvalMessage.setIsApprove(updateStatus == FormStatusConstant.FINISH ? 2 : 1);
//                    approvalMessage.setIsSend(1);
//                    approvalMessage.setDataSourceType(KT_TYPE);
//                    if (negativeInvestment.getDataSource().equals(YthConstant.DATA_NINGBO)) {
//                        approvalMessage.setDataSourceType(YthConstant.DATA_NINGBO);
//                        approvalMessage.setFilingUserName(UserCache.userIdToName(TokenUtil.getTokenUserId()));
//                        approvalMessage.setFormType(FormTypeConstant.IM_NEGATIVE_INVESTMENT);
//                        approvalMessage.setFilingCode(negativeInvestment.getCode());
//                    }
//                    approvalMessageService.save(approvalMessage);
//                }
//            }
//            negativeInvestment.setStatus(updateStatus);
//            updateById(negativeInvestment);
//            return true;
//        } catch (Exception e) {
//            log.error(ExceptionUtils.getFullStackTrace(e));
//            return false;
//        }
//    }
//
//    @Override
//    public void uploadFile(MultipartFile multipartFile){
//        try {
//            byte[] bytes = IOUtils.toByteArray(multipartFile.getInputStream());
//            InputStream inputStream = new ByteArrayInputStream(bytes);
//            List<Object> negativeList = new ArrayList<>();
//            List<Object> foribidList = new ArrayList<>();
//            List<Object> superviseList = new ArrayList<>();
//            EasyExcel.read(inputStream).build()
//                    .read(EasyExcel.readSheet(0).headRowNumber(1).head(NegativeInvestmentExcelBean.class)
//                            .registerReadListener(new PageReadListener<>(list -> negativeList.addAll(list))).build());
//            inputStream.reset();
//            EasyExcel.read(inputStream).build()
//                    .read(EasyExcel.readSheet(1).headRowNumber(1).head(NegativeForbidExcelBean.class)
//                            .registerReadListener(new PageReadListener<>(list -> foribidList.addAll(list))).build());
//            inputStream.reset();
//            EasyExcel.read(inputStream).build()
//                    .read(EasyExcel.readSheet(2).headRowNumber(1).head(NegativeSuperviseExcelBean.class)
//                            .registerReadListener(new PageReadListener<>(list -> superviseList.addAll(list))).build());
//            ImportExcelUtil.filterEmpty(negativeList);
//            ImportExcelUtil.filterEmpty(foribidList);
//            ImportExcelUtil.filterEmpty(superviseList);
//
//            List<NegativeInvestment> allList = getAllList(negativeList, foribidList, superviseList);
//            if (CollectionUtil.isNotEmpty(allList)){
//                allList.forEach(this::submit);
//            }
//        } catch (IOException e) {
//            e.printStackTrace();
//        } catch (IllegalAccessException e) {
//            e.printStackTrace();
//        }
//    }
//
//    /**
//     * @Description: //TODO excelBean 转换集合
//     * @Author: Take-off
//     * @Date: 9:18 AM 2023/3/28
//     * @Param: [negativeList, foribidList, superviseList]
//     * @return: java.util.List<com.plian.system.entity.im.NegativeInvestment>
//     **/
//    private List<NegativeInvestment> getAllList(List<Object> negativeList,List<Object> foribidList,List<Object> superviseList){
//        List<NegativeInvestment> negativeInvestments = new ArrayList<>();
//        List<NegativeForbid> negativeForbids = new ArrayList<>();
//        List<NegativeSupervise> negativeSupervises = new ArrayList<>();
//
//        String userId = TokenUtil.getTokenUserId();
//
//        for (Object object : negativeList) {
//            NegativeInvestmentExcelBean excelBean = (NegativeInvestmentExcelBean) object;
//            NegativeInvestment negativeInvestment = new NegativeInvestment();
//            negativeInvestment.setNegativeListName(excelBean.getNegativeListName());
//            negativeInvestment.setForbidExplain(excelBean.getForbidExplain());
//            negativeInvestment.setSuperviseExplain(excelBean.getSuperviseExplain());
//            negativeInvestment.setReportPerson(userId);
//            negativeInvestment.setReportTime(DateUtil.now());
//            negativeInvestments.add(negativeInvestment);
//        }
//        for (Object object : foribidList) {
//            NegativeForbidExcelBean excelBean = (NegativeForbidExcelBean) object;
//            NegativeForbid negativeForbid = new NegativeForbid();
//            negativeForbid.setNegativeListName(excelBean.getNegativeListName());
//            if (StringUtil.isNotBlank(excelBean.getSerialNumber())){
//                negativeForbid.setSerialNumber(Integer.valueOf(excelBean.getSerialNumber()));
//            }
//            negativeForbid.setForbidContent(excelBean.getForbidContent());
//            negativeForbids.add(negativeForbid);
//        }
//        for (Object object : superviseList) {
//            NegativeSuperviseExcelBean excelBean = (NegativeSuperviseExcelBean) object;
//            NegativeSupervise negativeSupervise = new NegativeSupervise();
//            negativeSupervise.setNegativeListName(excelBean.getNegativeListName());
//            if (StringUtil.isNotBlank(excelBean.getSerialNumber())){
//                negativeSupervise.setSerialNumber(Integer.valueOf(excelBean.getSerialNumber()));
//            }
//            negativeSupervise.setSuperviseContent(excelBean.getSuperviseContent());
//            negativeSupervises.add(negativeSupervise);
//        }
//        if (CollectionUtil.isNotEmpty(negativeForbids)){
//            Map<String, List<NegativeForbid>> mapByName = negativeForbids.stream().filter(m -> Optional.ofNullable(m.getNegativeListName()).isPresent()).collect(Collectors.groupingBy(NegativeForbid::getNegativeListName));
//            if (CollectionUtil.isNotEmpty(negativeInvestments)){
//                negativeInvestments.forEach( m ->{
//                    m.setNegativeForbid(mapByName.get(m.getNegativeListName()));
//                });
//            }
//        }
//        if (CollectionUtil.isNotEmpty(negativeSupervises)){
//            Map<String, List<NegativeSupervise>> mapByName = negativeSupervises.stream().filter(m -> Optional.ofNullable(m.getNegativeListName()).isPresent()).collect(Collectors.groupingBy(NegativeSupervise::getNegativeListName));
//            if (CollectionUtil.isNotEmpty(negativeInvestments)){
//                negativeInvestments.forEach( m ->{
//                    m.setNegativeSupervises(mapByName.get(m.getNegativeListName()));
//                });
//            }
//        }
//        return negativeInvestments;
//    }
//
//}
